#!/usr/bin/env python
import os
import sys
import subprocess

# Check if godot-cpp/ exists
if not os.path.exists("godot-cpp"):
    print("Directory godot-cpp/ not found. Cloning repository...")
    result = subprocess.run(
        ["git", "clone", "-b", "4.5", "https://github.com/godotengine/godot-cpp.git"],
        check=True,
        # capture_output=True
    )
    if result.returncode != 0:
        print("Error: Cloning godot-cpp repository failed.")
        Exit(1)
    print("Finished cloning godot-cpp repository.")



env = SConscript("godot-cpp/SConstruct")
env.Append(CPPPATH=["src/"])
sources = Glob("*.cpp")
sources += Glob("protocol/*.cpp")
sources += Glob("package/*.cpp")
sources += Glob("message/*.cpp")
sources += Glob("nanov1/*.cpp")
sources += Glob("nanov2/*.cpp")

doc_data = env.GodotCPPDocData("gen/doc_data.gen.cpp", source=Glob("doc_classes/*.xml"))
sources.append(doc_data)

if env["platform"] == "macos":
    library = env.SharedLibrary(
        "bin/addons/nanocodec/bin/libnanocodec.{}.{}.framework/libnano.{}.{}".format(
            env["platform"], env["target"], env["platform"], env["target"]
        ),
        source=sources,
    )
elif env["platform"] == "ios":
    if env["ios_simulator"]:
        library = env.StaticLibrary(
            "bin/addons/nanocodec/bin/libnanocodec.{}.{}.simulator.a".format(env["platform"], env["target"]),
            source=sources,
        )
    else:
        library = env.StaticLibrary(
            "bin/addons/nanocodec/bin/libnanocodec.{}.{}.a".format(env["platform"], env["target"]),
            source=sources,
        )
else:
    library = env.SharedLibrary(
        "bin/addons/nanocodec/bin/libnanocodec{}{}".format(env["suffix"], env["SHLIBSUFFIX"]),
        source=sources,
    )

Default(library)


# ���岿��Ŀ��·��
deploy_dir = "bin/addons/nanocodec"
bin_dir = deploy_dir + "/bin"

# ȷ��Ŀ��Ŀ¼����
env.Execute(Mkdir(bin_dir))

# ���� gdextension �ļ��� bin ��Ŀ¼
deploy_gdextension = env.Command(
    target = bin_dir + "/nanocodec.gdextension",
    source = "gdextension/nanocodec.gdextension",  # Դ�ļ�·��
    action = Copy("$TARGET", "$SOURCE")
)

# ���� README.md �������Ŀ¼
deploy_readme = env.Command(
    target = deploy_dir + "/README.md",
    source = "README.md",  # Դ README ·��
    action = Copy("$TARGET", "$SOURCE")
)

# ������������ΪĬ��Ŀ��
Default(deploy_gdextension, deploy_readme)